%This function is useed to generate a trigger to launch the TCSII
%stimulation. The trigger voltage is also applied on the AO1 and this
%connector can be use to send trigger to another device (e.g. EEG system).
%The NI must be first initialized.
%AC 12/19
function [data,time,temp]=TCSII_launch_NI(TCS,NI,recording_duration,foreperiod,postperiod,feedback_duration)
SR=NI.Rate;
 fid1 = fopen('log.bin', 'w') ;
    % add listener for the input (acquired data)
    lh_in=addlistener(NI,'DataAvailable',...
        @(src,event) logData(src,event, fid1)) ;
    % the handle function specified for the listener cannot increment a global
    % variable ==> have to write temporary results in a file (fid1)
%duration_bins
duration_bins=round((recording_duration+foreperiod+postperiod)*SR);
foreperiod_bins=round(foreperiod*SR);
postperiod_bins=postperiod*SR;
%neutral_volt
neutral_volt=0;
    
%prepare voltage matrix
volt_mat=zeros(duration_bins,2);
volt_mat(:,:)=neutral_volt;

%dx1
dx1=foreperiod_bins+1;
dx2=duration_bins-postperiod_bins;

%active temperatures
volt_mat(dx1:dx1+50,:)=5;

lh_out = addlistener(NI,'DataRequired', ...
            @(src,event) src.queueOutputData(volt_mat));
a=[];
c=[];
msg=[];
ab=[];
cb=[];
msgb=[];

%launch stimulation
flushoutput(TCS);
flushinput(TCS);

%queue the data to NI
queueOutputData(NI,volt_mat);


  n_bins_to_load=round(feedback_duration/10);
    if n_bins_to_load>0
startBackground(NI);
disp('Data sent to NI');
    t = NaN(n_bins_to_load,5) ;
        idx_data = 1 ;     
        for i=1:n_bins_to_load
            [ab,cb,msgb] = fscanf(TCS) ;
            tmp =str2num(ab) ; 
            if length(tmp)==5
                t(idx_data,:) = tmp ; 
                idx_data = idx_data + 1 ; 
            end
            
        end
        temp=t;
        
        pause((duration_bins-feedback_duration)/1000);

delete(lh_in);
delete(lh_out);
disp('NI finished');

fclose(fid1) ; 

% Read the data of the current session to output them
fid2 = fopen('log.bin', 'r') ;
[raw_data, count] = fread(fid2, [3, Inf], 'double') ; 
% [9, Inf] = size of data to read
fclose(fid2) ;

% same format as when foreground acquisition is used
time = raw_data(1,:)' ; 
data = raw_data(2:end,:)' ; 

    else
        [data,time]=startForeground(NI);
        disp('Data sent to NI');
        temp='not recorded';
        delete(lh_in);
delete(lh_out);
disp('NI finished');

fclose(fid1) ; 
    end

end
 